package ch.creasystem.tennis.playermgmt.facade;

import java.util.Date;
import java.util.List;

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import ch.creasystem.tennis.playermgmt.entities.Player;

/**
 * Bean implementation class PlayerMgmtService
 */
@Stateless
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public class PlayerMgmtServiceBean implements PlayerMgmtService {

	@PersistenceContext
	EntityManager em;
    

	public Player createPlayer(String name, String lastname, Date birthdate) {
    	Player player = new Player();
    	player.setFirstname(name);
    	player.setLastname(lastname);
    	player.setBirthdate(new java.sql.Date(birthdate.getTime()));
    	
    	this.em.persist(player);
    	return player;
    }
    
    @SuppressWarnings("unchecked")
	public List<Player> getAllPlayers() {
    	Query query = em.createQuery("SELECT p FROM Player p");
    	List<Player> resultList = query.getResultList();
		return resultList;
    	}

	public Player getPlayerById(Long playerId) {
		return em.find(Player.class, playerId);
	}
	
	public Player updatePlayer(Player player) {
		return em.merge(player);		
	}
	
	public void deletePlayer(Long playerId) {
		Player player = em.find(Player.class, playerId);
		if (player != null) {
			em.remove(player);
		}
	}
}
